package com.miukoo.aikao.admin.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.miukoo.aikao.admin.service.JwtUserRedisService;
import com.miukoo.aikao.core.dtos.ApiResult;
import com.miukoo.aikao.core.pojos.SecurityUser;
import com.miukoo.aikao.core.utils.ApiUtils;
import com.miukoo.aikao.core.utils.AppUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author miukoo<miukoo@126.com>
 * @Date 2020/11/23  
 * @Version 1.0
 */
@Component
public class SecurityLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtUserRedisService jwtUserRedisService;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityUser user = AppUserUtils.getUser();
        jwtUserRedisService.clearUser(user);
        ApiResult<String> success = ApiUtils.success();
        String result = objectMapper.writeValueAsString(success);
        response.setHeader("token", "");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.OK.value());
        response.getOutputStream().write(result.getBytes());
    }
}
